﻿@page "/canvaslines"

@inject IJSRuntime JS

<canvas id="myCanvas" width="500" height="500" @onmousedown="CanvasMouseDown" @onmousemove="CanvasMouseMove" @onmouseup="CanvasMouseUp" @onmouseleave="CanvasMouseLeave"></canvas>

@code {
    private bool isDrawing = false;
    private double startX = 0, startY = 0, currentX = 0, currentY = 0;

    private async Task CanvasMouseDown(MouseEventArgs e)
    {
        isDrawing = true;
        (startX, startY) = (e.ClientX, e.ClientY);
        currentX = startX;
        currentY = startY;

        // 你可以在这里添加逻辑来开始新的线条，或者选择现有的线条（如果需要）
    }

    private async Task CanvasMouseMove(MouseEventArgs e)
    {
        // if (!isDrawing) return;


        // (currentX, currentY) = (e.ClientX, e.ClientY);

        // // 调用JavaScript函数来绘制直线（从起点到当前鼠标位置）
        // await JS.InvokeVoidAsync("canvasInterop.drawLine", startX, startY, currentX, currentY, "black");

        // // 更新起点为当前鼠标位置，以便绘制下一段直线（如果需要）
        // startX = currentX;
        // startY = currentY;
    }

    private async Task CanvasMouseUp(MouseEventArgs e)
    {
        if (!isDrawing) return;
        (currentX, currentY) = (e.ClientX, e.ClientY);
        // 调用JavaScript函数来绘制直线（从起点到当前鼠标位置）
        await JS.InvokeVoidAsync("canvasInterop.drawLine", startX, startY, currentX, currentY, "black");
        // 更新起点为当前鼠标位置，以便绘制下一段直线（如果需要）
        startX = currentX;
        startY = currentY;


        isDrawing = false;
        // 在这里处理线条的结束，如果需要的话
    }

    private async Task CanvasMouseLeave(EventArgs e)
    {
        isDrawing = false;
        // 在这里处理线条的结束，如果需要的话
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await JS.InvokeVoidAsync("import", "./canvasInterop.js");
        if (firstRender)
        {
           
        }
    }

}